﻿using CDSysLDManageProject.BYDTableAdapters;
using Ivi.Visa.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace CDSysLDManageProject
{
    public partial class Form1 : Form
    {
        
        T_TrayCellDataTableAdapter trayinfo = new T_TrayCellDataTableAdapter();
        
        DataTable dttraycellinfo = new DataTable();
        DataTable dtocvdata = new DataTable();
        static SocketTest st1 = new SocketTest();
        static SocketTest st2 = new SocketTest();
        int allowngcount = 3;
        MySocket iSocket;
        Thread receivethread;//收数线程
        Thread PackPickthread;//分包初解析线程
        List<byte> RecBufferList = new List<byte>();
        CDPackPick packPick;
        KapjinEqProtocol kep ;
        bool handInput = true;
        string ip1 = System.Configuration.ConfigurationManager.AppSettings["WCSAddress"];
        int port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort"]);
        int port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort1"]);
        int port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort2"]);
        DateTime starttime;
        DateTime endtime;
        int allowocv;
        int allowdcir;
        Double ocvhigh;
        Double ocvlow;
        string testresult = "";         //OCV测定结果
        public Form1()
        {
            InitializeComponent();
        }

        IResourceManager rm = null;
        //string strRd;
        //System.Array block;
        IMessage session = null;
        private void Form1_Load(object sender, EventArgs e)
        {

            //this.MaximizeBox = false; /// 设置最大化按钮是否有效 
            richtbxmsg.AppendText("充电完成,已收到充放电结果!\r\n");
            tbxdcirmsg.Text = "DCIR测试中";
            tbxdcirmsg.BackColor = Color.LightGreen;
            tbxdcirtrayno.Text = "H024202-C15";
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            //根据堆垛机是否就位来控制ECS的销钉
            //iSocket = new MySocket();
            //st1.CreateClient(ip1, port);
            //st2.CreateClient(ip1, port1);
            
            dttraycellinfo.Columns.Add("trayno");
            dttraycellinfo.Columns.Add("cellno");
            dttraycellinfo.Columns.Add("chno");
            dttraycellinfo.Columns.Add("cellsts");
            dttraycellinfo.Columns.Add("ocvdata", typeof(double));
            dtocvdata.Columns.Add("cellno");
            dtocvdata.Columns.Add("chno");
            dtocvdata.Columns.Add("ocvdata",typeof(double));
            dtocvdata.Columns.Add("cellsts");

            CreateArgXmlFile();
            //bginitial.RunWorkerAsync();
            bgReplayECS.RunWorkerAsync();
            
            bgWriteLog.RunWorkerAsync();
            ///////bgBeginOCV.RunWorkerAsync();
           
        }

        /// <summary>
        /// 接收
        /// </summary>
        private void receiveByte()
        {
            try
            {
                while (true)
                {
                  int reclength =  iSocket.SocketReceive(RecBufferList);
                  if (reclength < 1)
                  {
                      Thread.Sleep(1000);
                  }
                  else
                  {
                      //string str1 = "";
                  }
                }
            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);

            }
        }

        private void BufferPackPick()
        {
           
                while (true)
                {
                    try
                    {
                        packPick.bufferHandle(RecBufferList);
                     }
                     catch (Exception ex)
                     {
                         Exceptionlog.InsertException(ex);
                     }
                    
                }
          
        }

        private void bgwAliveSignal_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    if (!kep.AliveSignal())
                    {
                        Exceptionlog.InsertException("心跳超时", "与电源通讯的心跳超时，与电源设备的以太网通讯可能发送异常。");
                        Thread.Sleep(5000);
                    }
                    else
                    {
                        Thread.Sleep(20000);
                    }
                }
                catch (Exception ex)
                {
                    Exceptionlog.InsertException(ex);
                }

            }
        }

        private void timerSynTime_Tick(object sender, EventArgs e)
        {
            timerSynTime.Stop();
            try
            {
                if (!kep.SynchronizeTime())
                {
                    Exceptionlog.InsertException("同步时间异常", "与电源通讯同步系统时间时，电源响应为：erro。");
                }

            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);
            }
            timerSynTime.Start();
        }


      
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

        private void bg_DoWork(object sender, DoWorkEventArgs e)
        {

            while (true)
            {

                if (!(GParam.RecListDic.ContainsKey("EDD") && GParam.RecStringDic.ContainsKey("EDD")))
                {
                    Thread.Sleep(500);
                    continue;
                    
                }
                if (GParam.RecListDic["EDD"].Count > 0)
                {
                    this.Invoke(new EventHandler(delegate
                    {
                        richtbxmsg.AppendText("充电完成,已收到充放电结果!\r\n");
                    }));
                    

                    //Thread.Sleep(200);

                    bool flag = kep.StepResult();
                    if (flag == true)
                    {

                    }
                    else
                    {
                        //richtbxmsg.AppendText("回复ECS充电完成失败！可能是由于数据解析错误导致的\r\n");
                        Log.SystemError.Add("回复ECS充电完成失败！可能是由于数据解析错误导致的");
                        Thread.Sleep(200);
                    }
                    Thread.Sleep(1000);

                }
                

                //if (!(GParam.RecListDic.ContainsKey("EPF") && GParam.RecStringDic.ContainsKey("EPF")))
                //{
                //    Thread.Sleep(500);
                //    continue;

                //}
                //if (GParam.RecListDic["EPF"].Count > 0)
                //{
                //    this.Invoke(new EventHandler(delegate
                //    {
                //        richtbxmsg.AppendText("充电完成,已收到充放电完成信号!\r\n");
                //    }));




                //    bool flag = kep.ProcessFinish();
                //    if (flag == true)
                //    {

                //    }
                //    else
                //    {
                //        //richtbxmsg.AppendText("回复ECS充电完成失败！可能是由于数据解析错误导致的\r\n");
                //        Log.SystemError.Add("回复ECS充电完成信号失败！可能是由于数据解析错误导致的");
                //        Thread.Sleep(200);
                //    }
                //    Thread.Sleep(1000);

                //}
                
            }
        }

        
       

        
        public string ReadRightValue(string  eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }

                    }
                    else if (st1.Connected() == true)
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");
                        
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st1.Connected())
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");
                       
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }

        public string ReadRightValueTest(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 100 && recvalue != expectvalue)
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");

                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }

                    }
                    else if (st1.Connected() == true)
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");
                        //Log.Trace.Add("当前511寄存器地址是" + recvalue);
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");

                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st1.Connected())
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");

                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }


        //校验并发送读指令
        public string ReadRightValue2(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st2.receivedata(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }





        //校验并发送写指令
        public void WriteRightValue(string eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st1.Connected() == false)
                {
                    //richtbxmsg.AppendText("网络连接断开");
                    richtbxmsg.AppendText("网络连接断开\r\n");
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st1.Connected() == false)
                    {
                        ReConnect();
                    }

                }
                else if (st1.Connected())
                {
                    sendflag = st1.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(200);
                    recvalue = st1.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //校验并发送写指令
        public void WriteRightValue2(string   eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st2.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");
                     
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st2.Connected() == false)
                    {
                        ReConnect2();
                    }

                }
                else if (st2.Connected())
                {
                    sendflag = st2.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(200);
                    recvalue = st2.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //连接网络
        private void ReConnect()
        {
            if (!st1.Connected())
            {
                try
                {
                    st1.CreateClient(ip1, port1);
                }
                catch (Exception)
                {


                }

            }
            else
            {

                richtbxmsg.AppendText("网络连接恢复1\r\n");
                 
                return;
            }
        }

        //连接网络
        private void ReConnect2()
        {
            if (!st2.Connected())
            {
                try
                {
                    st2.CreateClient(ip1, port2);
                }
                catch (Exception)
                {


                }

            }
            else
            {

                richtbxmsg.AppendText("网络连接恢复2,port2:" + port2 + "r\n");

                return;
            }
        }

   
        private void bgBeginProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            
            
        }

        private void button14_Click(object sender, EventArgs e)
        {
            string sr1 = tbxvalue.Text;
            tbxvalue.Text = ReadRightValue2(sr1,1,"notnull");
            //DateTime starttime = DateTime.Now;
            //int allowngcount = 3;
            //string testresult = "+3.26770200E+00,+3.27504720E+00,+1.87600000E-04,+1.26800000E-04,+7.46000000E-05,+1.83300000E-04,+1.70500000E-04,+1.25800000E-04,+1.16200000E-04,+1.02530000E-03,+1.97200000E-04,+8.21000000E-05,+1.37910000E-03,+4.27781100E-01,+3.61964500E-01,+7.99000000E-05";
            //string trayno = "H001622-C19";
            //string[] list = splitData(testresult);
            //DataTable dttrayinfo = new DataTable();
            //int ngcount = 0;
            //try
            //{
            //    dttrayinfo = trayinfo.GetCellNoByTrayNo(trayno);
            //    ngcount++;
            //}
            //catch (Exception ex)
            //{
            //    Log.SystemError.Add("根据托盘号查询电池条码失败！" + ex.ToString());
            //    ngcount++;
            //}
            //while (dttrayinfo.Rows.Count == 0 && ngcount <= allowngcount)
            //{
            //    dttrayinfo = trayinfo.GetCellNoByTrayNo(trayno);
            //    ngcount++;
            //}
            //DateTime endtime = DateTime.Now;
            //CreateOCVCsv(dttrayinfo, trayno, list, starttime, endtime);
            //SaveOCVDataToDB(trayno, list, dttrayinfo);
        }

     

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            receivethread.Abort();
            receivethread.Interrupt();
            PackPickthread.Abort();//分包初解析线程
            PackPickthread.Interrupt();
            Application.ExitThread();
            
            
        }


        //获取托盘信息
        public string ReadTrayNo(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }

                    }
                    else if (st1.Connected() == true)
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st1.receiveTrayNo(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st1.Connected())
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st1.receiveTrayNo(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }

        //获取托盘信息
        public string ReadTrayNo2(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";

                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";

                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }


        ////获取数据库里的架台信息
        //public string  GetStageInfoFromDB(string trayno)
        //{
        //    string traytype = trayno.Substring(trayno.Length - 3, 3);
        //    if (traytype == "C19")
        //    {

        //    }
        //    else if (traytype == "C12" || traytype == "C15")
        //    { 
        //        traytype = "C15";
        //    }
        //    DataTable dbss = new DataTable();
        //    dbss = stageinfo.GetStageStatus(traytype);
        //    if (dbss.Rows.Count > 0)
        //    {
        //        string stagelocation = dbss.Rows[0]["stagelocation"].ToString();
        //        return stagelocation;

        //    }
            
        //    return "";
        //}

        //public string GetRecipeID(string traytype)
        //{
        //    DataTable dtrecipeinfo = new DataTable();
        //    dtrecipeinfo = recipeinfo.GetRecipeInfo();
        //    if (dtrecipeinfo.Rows.Count > 0)
        //    {
        //        DataRow[] dr = dtrecipeinfo.Select(" traytype='"+traytype+"'");
        //        if (dr.Length > 0)
        //        {
        //            return dr[0]["recipeid"].ToString();
        //        }
        //        else
        //        {
        //            richtbxmsg.AppendText("请设置正确的托盘类型\r\n");
        //            tbmsg.BackColor = Color.Red;
        //            return "";
        //        }

        //    }
        //    return "";
            
        //}

       
     
     
        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void bginitial_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {

                //接收线程
                receivethread = new Thread(receiveByte);
                receivethread.Start();
                //分包解析线程
                PackPickthread = new Thread(BufferPackPick);
                PackPickthread.Start();
                packPick = new CDPackPick();
                kep = new KapjinEqProtocol(iSocket);
                bgwAliveSignal.RunWorkerAsync();

                //timerSynTime.Enabled = true;
                

            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);
                return;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

            kep.AliveSignal();

            if (!kep.AliveSignal())
            {
                Exceptionlog.InsertException("心跳超时", "与电源通讯的心跳超时，与电源设备的以太网通讯可能发送异常。");
                MessageBox.Show("与ECS连接异常");
                //Thread.Sleep(10000);
            }
            else
            {
                MessageBox.Show("与ECS连接正常");
                //Thread.Sleep(5000);
            }

            //if (kep.SynStageStatus().Count>0)
            //{
               
            //    MessageBox.Show("与ECS连接正常");
            //    //bgFreshStageSts.RunWorkerAsync();
            //    //WriteRightValue(30, 1, 0);

            //    //WriteRightValue(31, 1, 0);

            //    ////From 
            //    //WriteRightValue(32, 1, 0);
            //    //WriteRightValue(33, 1, 0);
            //    //WriteRightValue(34, 1, 0);

            //    ////To的值
            //    //WriteRightValue(35, 1, 0);
            //    //WriteRightValue(36, 1, 0);
            //    //WriteRightValue(37, 1, 0);

            //    ////更新
            //    //WriteRightValue(10, 1, 0);
            //    //WriteRightValue(11, 1, 0);
            //    //WriteRightValue(90, 1, 0);
            //    //WriteRightValue(91, 1, 0);
            //    //WriteRightValue(92, 1, 0);
            //    //WriteRightValue(93, 1, 0);
            //    //WriteRightValue(100, 1, 0);
            //}
            //else
            //{
            //    MessageBox.Show("与ECS连接异常");
            //}
        }

       

       

        private void bgWriteLog_DoWork(object sender, DoWorkEventArgs e)
        {


            while (true)
            {
                while (Log.Trace.Count > 0)
                {
                    Log.WriteLog(LogFile.Trace, Log.Trace[0]);
                    if (Log.Trace.Count > 0)
                    {
                        Log.Trace.RemoveAt(0);
                    }

                }
                while (Log.MeasureWarning.Count > 0)
                {
                    Log.WriteLog(LogFile.MeasureWarning, Log.MeasureWarning[0]);
                    if (Log.MeasureWarning.Count > 0)
                    {
                        Log.MeasureWarning.RemoveAt(0);
                    }
                }
                while (Log.MeasureError.Count > 0)
                {
                    Log.WriteLog(LogFile.MeasureError, Log.MeasureError[0]);
                    if (Log.MeasureError.Count > 0)
                    {
                        Log.MeasureError.RemoveAt(0);
                    }
                }
                while (Log.SQL.Count > 0)
                {
                    Log.WriteLog(LogFile.SQL, Log.SQL[0]);
                    if (Log.SQL.Count > 0)
                    {
                        Log.SQL.RemoveAt(0);
                    }
                }
                while (Log.SystemError.Count > 0)
                {
                    Log.WriteLog(LogFile.SystemError, Log.SystemError[0]);
                    if (Log.SystemError.Count > 0)
                    {
                        Log.SystemError.RemoveAt(0);
                    }
                }
                while (Log.ReciveFromECS.Count > 0)
                {
                    Log.WriteLog(LogFile.ReciveFromECS, Log.ReciveFromECS[0]);
                    if (Log.ReciveFromECS.Count > 0)
                    {
                        Log.ReciveFromECS.RemoveAt(0);
                    }
                }
                while (Log.SendToECS.Count > 0)
                {
                    Log.WriteLog(LogFile.SendToECS, Log.SendToECS[0]);
                    if (Log.SendToECS.Count > 0)
                    {
                        Log.SendToECS.RemoveAt(0);
                    }
                }

                Thread.Sleep(1000);
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (kep.StageReservation("001001001"))
            {
                MessageBox.Show("架台预约成功");

            }
            
        }

        private void bgBeginOCV_DoWork(object sender, DoWorkEventArgs e)
        {
            DataTable dttemp = new DataTable();
            dttemp = (DataTable)e.Argument;
            richtbxmsg.Clear();
            msgwarn.Text = "";
            msgwarn.BackColor = Color.White;
            while (true)
            {

                string rec510 = ReadRightValue("510", 1, "0001");
                if (rec510 == "0001")
                {
                dttraycellinfo.Clear();
                dtocvdata.Clear();
                this.Invoke(new Action(() =>
                {
                    dgvocvdata.DataSource = dtocvdata.Copy();
                }
                                           ));
                msgwarn.Text = "OCV搬入中";
                msgwarn.BackColor = Color.SpringGreen;
                string trayno = ReadTrayNo("530", 10, "notnull");
                if (trayno.Length >= 11)
                {
                    trayno = trayno.Substring(0, 11);
                    tbxtrayno.Text = trayno;
                }
                else
                {
                    while (trayno.Length < 11)
                    {
                        trayno = ReadTrayNo("530", 10, "notnull");
                    }
                }


                if (trayno.Contains("C15"))
                {
                    WriteRightValue("10", 1, 1);
                    richtbxmsg.AppendText("w10已经写1\r\n");
                }
                else if (trayno.Contains("C12"))
                {
                    WriteRightValue("10", 1, 2);
                    richtbxmsg.AppendText("w10已经写2\r\n");
                }
                else if (trayno.Contains("C19"))
                {
                    WriteRightValue("10", 1, 3);
                    richtbxmsg.AppendText("w10已经写3\r\n");
                }

                string receive510temp = ReadRightValue("510", 1, "0000");
                while (ReadRightValue("510", 1, "notnull") != "0000")
                {
                    Thread.Sleep(300);
                }
                string receive510 = ReadRightValue("510", 1, "0000");
                if (receive510 == "0000")
                {
                    richtbxmsg.AppendText("已收到510为0的应答信号\r\n");
                    WriteRightValue("10", 1, 0);
                }
                else
                {
                    msgwarn.Text = "PLC应答异常";
                    msgwarn.BackColor = Color.Red;
                    break;
                }

                //int j = 0;
                //while (ReadRightValue("511", 1, "0001") != "0001")
                //{
                    
                //    richtbxmsg.AppendText("等待PLC夹紧托盘计数中"+j+"\r\n");
                //    Thread.Sleep(500);
                //    j++;
                //}

                string rec511 = ReadRightValue("511", 1, "0001");
                
                if (rec511 == "0001")
                {
                    WriteRightValue("11", 1, 1);
                    string receive511 = ReadRightValue("511", 1, "0000");
                    if (receive511 == "0000")
                    {
                        WriteRightValue("11", 1, 0);
                        //OCV测定开始
                        if (allowocv == 1)
                        {
                            starttime = DateTime.Now;

                            testresult=AgilentMeasure();
                            while (testresult=="")
                            {
                                CloseCOMPORT();
                                msgwarn.Text = "OCV再测试中";
                                msgwarn.BackColor = Color.Yellow;
                                starttime = DateTime.Now;
                                testresult = AgilentMeasure();
                            }
                            
                            try
                            {
                                string[] list = splitData(testresult);
                                if (list.Length == 0)
                                {
                                    msgwarn.Text = "读取OCV测试数据异常";
                                    msgwarn.BackColor = Color.Red;
                                    return;
                                }
                                if (handInput)
                                {

                                    for (int i = 1; i <= 16; i++)
                                    {
                                        DataRow dr = dttraycellinfo.NewRow();
                                        dr["chno"] = i;
                                        dr["trayno"] = trayno;
                                        DataRow[] dr1 = dttemp.Select("chno='" + i + "'");
                                        dr["cellno"] = dr1[0]["cellno"];
                                        
                                        dttraycellinfo.Rows.Add(dr);
                                    }

                                    for (int i = 0; i < 16; i++)
                                    {//通道是反的。所以需要反转数据
                                        DataRow[] dr = dttraycellinfo.Select("chno='"+(16-i)+"'" );
                                        dr[0]["ocvdata"] = Double.Parse(list[i]);
                                        dr[0]["cellsts"] = JudgeCellSts(Double.Parse(list[i]));

                                    }

                                    //创建OCV cvs
                                    CreateOCVCsv(dttraycellinfo, trayno, list, starttime, endtime);


                                    this.Invoke(new Action(() =>
                                    {
                                        dgvocvdata.DataSource = dtocvdata.Copy();
                                    }
                                    ));

                                    //将OCV测定结果存储到DB
                                    SaveOCVDataToDB(trayno, dttraycellinfo);
                                }
                                else
                                {
                                    //需要连上服务器才可以解除注释
                                    DataTable dttrayinfo = new DataTable();
                                    int ngcount = 0;
                                    try
                                    {
                                        dttrayinfo = trayinfo.GetCellNoByTrayNo(trayno);
                                        ngcount++;
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.SystemError.Add("根据托盘号查询电池条码失败！" + ex.ToString());
                                        ngcount++;
                                    }



                                    while (dttrayinfo.Rows.Count == 0 && ngcount <= allowngcount)
                                    {
                                        dttrayinfo = trayinfo.GetCellNoByTrayNo(trayno);
                                        ngcount++;
                                    }

                                    if (dttrayinfo.Rows.Count > 0 && ngcount <= allowngcount)
                                    {
                                        //将托盘信息级电池NG结果存储到dttraycellinfo
                                        for (int i = 1; i <= 16; i++)
                                        {
                                            DataRow dr = dttraycellinfo.NewRow();
                                            dr["chno"] = i;
                                            dr["trayno"] = trayno;
                                            DataRow[] dr1 = dttrayinfo.Select("CH_NO='" + i + "'");
                                            dr["cellno"] = dr1[0]["CELL_NO"];
                                            //dr["cellno"] = "HQI19C15GRNS0122" + i.ToString().PadLeft(2, '0');
                                            dttraycellinfo.Rows.Add(dr);
                                        }

                                        for (int i = 0; i < 16; i++)
                                        {
                                            DataRow[] dr = dttraycellinfo.Select("chno='" + (16 - i) + "'");
                                            dr[0]["ocvdata"] = Double.Parse(list[i]);
                                            dr[0]["cellsts"] = JudgeCellSts(Double.Parse(list[i]));

                                        }


                                        //创建OCV cvs
                                        CreateOCVCsv(dttraycellinfo, trayno, list, starttime, endtime);

                                        this.Invoke(new Action(() =>
                                        {
                                            dgvocvdata.DataSource = dtocvdata.Copy();
                                        }
                                    ));
                                        //将OCV测定结果存储到DB
                                        SaveOCVDataToDB(trayno, dttraycellinfo);
                                    }
                                    else
                                    {
                                        Log.SystemError.Add("根据托盘号查询电池条码失败！");
                                        break;
                                    }

                                }
                            }
                            catch (Exception ex)
                            {

                                richtbxmsg.AppendText("生成OCV测定结果失败\r\n");
                                Log.SystemError.Add("生成OCV测定结果失败"+ex.ToString());
                            }



                        }
                        else
                        {
                            msgwarn.Text = "已跳过OCV测定";
                            msgwarn.BackColor = Color.Yellow;
                        }

                    }
                    else
                    {
                        richtbxmsg.AppendText("PLC511复位应答异常!\r\n");
                    }

                //OCV测定结束
                try
                {
                    session.Close();
                }
                catch (Exception ex)
                {

                    Log.SystemError.Add("session.Close()失败，原因是:"+ex.ToString());
                }
                //如果DCIR未完成的话则不搬出,这里需要PLC给个DCIR是否载荷的状态
                while (bgBeginDCIRTest.IsBusy)
                {
                    Thread.Sleep(200);
                }
                msgwarn.Text = "OCV测定完成开始搬出";
                msgwarn.BackColor = Color.SpringGreen;
                WriteRightValue("12", 1, 1);
                string rec512 = ReadRightValue("512", 1, "0001");

                        if (rec512 == "0001")
                        {
                            WriteRightValue("12", 1, 0);
                            msgwarn.Text = "OCV测试搬出中";
                            msgwarn.BackColor = Color.SpringGreen;
                            //搬出后开始DCIR
                            bgBeginDCIRTest.RunWorkerAsync();
                            //return;
                            break;
                        }
                        else
                        {
                            msgwarn.Text = "PLC512应答异常";
                            msgwarn.BackColor = Color.Red;
                            richtbxmsg.AppendText("PLC512应答异常,应为1\r\n");
                        }



                    }
                    else
                    {
                        Log.SystemError.Add("PLC511值为:" + rec511);
                        msgwarn.Text = "PLC511应答异常";
                        msgwarn.BackColor = Color.Red;
                        richtbxmsg.AppendText("PLC应答511异常12\r\n");
                    }

                }

            }
        }

        public string  AgilentMeasure()
        {

            try
            {
                try
                {
                    session.Close();
                }
                catch (Exception)
                {

                }
                InitialAgilentEquip();
                            
            }
            catch (Exception ex)
            {

                Log.SystemError.Add("发送OCV测试指令失败" + ex.ToString());
                msgwarn.Text = "与安捷伦通讯异常";
                richtbxmsg.AppendText("与安捷伦通讯异常");
                msgwarn.BackColor = Color.Red;
                try
                {
                    session.Close();
                }
                catch (Exception ex1)
                {
                    Log.SystemError.Add("session.Close()失败，原因是:" + ex1.ToString());
                }
                return "";
            }
            starttime = DateTime.Now;
            msgwarn.Text = "开始OCV测定";
            msgwarn.BackColor = Color.SpringGreen;
            //10S测试时间
            Thread.Sleep(10000);
            
            try
            {
                testresult = session.ReadString(300);
                endtime = DateTime.Now;
                return testresult;
            }
            catch (Exception ex)
            {
                msgwarn.Text = "读取OCV测试数据异常";
                msgwarn.BackColor = Color.Red;
                Log.SystemError.Add("读取OCV测试数据异常" + ex);
                try
                {
                    session.Close();
                }
                catch (Exception ex1)
                {
                    Log.SystemError.Add("session.Close()失败，原因是:" + ex1.ToString());
                }
                return "";
            }

        }


        public string JudgeCellSts(double ocv)
        {
            if (ocv > ocvlow && ocv < ocvhigh)
            {
                return "00";
            }
            else
            {
                return "05";
            }
        }

        public String[] splitData(string str1)
        {
            String[] list1 = str1.Split(',');
            return list1;
        }

        //创建OCV Csv     将测定结果存到指定路径下
        public void CreateOCVCsv(DataTable dttrayinfo, string TrayNo, string[] list, DateTime starttime, DateTime endtime)
        {

            double ocvdata=0;
            string cellno="";
            string cellsts="";
            DateTime date = DateTime.Now;
            string exportPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"\\OCV2Data"; //生成CSV路径
            string NewFileName = TrayNo + DateTime.Now.Year.ToString().Substring(2, 2) + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0') + ".csv";
            exportPath = exportPath + "\\" + date.Year.ToString() + "\\" + date.Month.ToString().PadLeft(2, '0') + "\\" + date.Day.ToString().PadLeft(2, '0');
            if (!Directory.Exists(exportPath))
            {
                Directory.CreateDirectory(exportPath);
            }
            exportPath = exportPath + "\\"  + NewFileName;

            
            if (!File.Exists(exportPath))
            {

                FileStream fs1 = new FileStream(exportPath, FileMode.Create, FileAccess.Write);//创建写入文件 
                StreamWriter sw = new StreamWriter(fs1);

                sw.WriteLine("CellNo,ChNo,OCV1,ACIR,StartTime,Flag,OCV2,OCV3,EndTime,Reserved,Reserved,Reserved,Reserved,ACIR_Before,Reserved,Reserved,Reserved,ACIR_Calib,Reserved,Reserved");//开始写入值

                for (int i = 0; i < 32;i++ )
                {
                    if (i < 16)
                    {
                        DataRow dr = dtocvdata.NewRow();
                        dr["chno"] = i+1;
                        DataRow[] dr1 = dttrayinfo.Select("chno='" + (i+1) + "'");
                        if (dr1.Length > 0)
                        {
                             ocvdata = TransVtoRight(dr1[0]["ocvdata"].ToString(), 6);
                             cellno = dr1[0]["cellno"].ToString();
                             cellsts = dr1[0]["cellsts"].ToString();
                        }
                        if (cellsts == "05")
                        {
                            dr["cellsts"] = "NG";
                        }
                        else
                        {
                            dr["cellsts"] = "OK";
                        }
                        
                        dr["cellno"] = cellno;
                        dr["ocvdata"] = ocvdata;
                        dtocvdata.Rows.Add(dr);
                        sw.WriteLine(dttrayinfo.Rows[i]["cellno"] + "," + (i + 1) + "," + ocvdata+ "," + 0 + "," + starttime + "," + "00000000" + "," + 0 + "," + 0 + "," + endtime + "," + 1 + "," + 17109 + "," + (i + 1) + "," + ocvdata + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0);
                    }
                    else
                    {
                        sw.WriteLine("" + "," + (i + 1) + "," + "0" + "," + 0 + "," + starttime + "," + "00000000" + "," + 0 + "," + 0 + "," + endtime + "," + 1 + "," + 17109 + "," + (i + 1) + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0 + "," + 0);
                    }
                    
                }
                sw.Close();
                fs1.Close();

            }
           


        }


        /// <summary>
        /// 将OCV结果存到数据库
        /// </summary>
        public void SaveOCVDataToDB(string TrayNo, DataTable dttrayinfo)
        {

            T_OCVResultDataTableAdapter ocvresult = new T_OCVResultDataTableAdapter();
            T_MESResultMessageTableTableAdapter mesmsg = new T_MESResultMessageTableTableAdapter();
            Double ocv1voltage = 0; //
            Double ocv2voltage = 0;
            Double ocvdeltav = 0;   //ocv1-ocv2
            DataTable dtocvdata = new DataTable();//OCV1数据的dt
            DateTime finishtime = DateTime.Now; //测试完成时间
            if (dttrayinfo.Rows.Count >= 16)
            {
                for (int i = 0; i < 16; i++)
                {
                    dtocvdata.Clear();
                    ocv1voltage = 0; //
                    ocv2voltage = 0;
                    ocvdeltav = 0;   //ocv1-ocv2
                    DataRow[] dr1 = dttrayinfo.Select("chno='" + (i + 1) + "'");
                    if (dr1.Length > 0)
                    {
                        ocv2voltage = double.Parse(dr1[0]["ocvdata"].ToString());
                        //先将OCV数据插入到神亚数据库的T_OCVResultData表
                        int ocv2count = int.Parse(ocvresult.GetOCV2CountByCellNo(dr1[0]["cellno"].ToString()).ToString());
                        if (ocv2count > 0)
                        {
                            try
                            {
                                ocvresult.DeleteOcv2DataByCellNo(dr1[0]["cellno"].ToString());
                                ocvresult.InsertOCVResult(dr1[0]["cellno"].ToString(), 2, 0, ocv2voltage, 0, 0, 0, 0, 0, 0, 0);
                            }
                            catch (Exception ex)
                            {
                                Log.SQL.Add("将" + dr1[0]["cellno"].ToString() + "的电池的OCV2数据插入到数据库失败!"+ex.ToString());
                            }
                        }
                        else
                        {
                            try
                            {
                                ocvresult.InsertOCVResult(dr1[0]["cellno"].ToString(), 2, 0, ocv2voltage, 0, 0, 0, 0, 0, 0, 0);
                            }
                            catch (Exception ex)
                            {
                                Log.SQL.Add("将" + dr1[0]["cellno"].ToString() + "的电池的OCV2数据插入到数据库失败!"+ex.ToString());
                            }
                        }
                        

                        //根据电池编号查询OCV1电压，计算OCVDeltaV。

                        try
                        {
                            dtocvdata = ocvresult.GetOCV1DataByCellNo(dr1[0]["cellno"].ToString());
                        }
                        catch (Exception ex)
                        {
                            Log.SQL.Add("查询" + dr1[0]["cellno"].ToString() + "的OCV1数据插失败!" + ex);
                        }
                    }




                    if (dtocvdata.Rows.Count >= 1)
                    {
                        ocv1voltage = double.Parse(dtocvdata.Rows[0]["OCV1_DATA"].ToString());
                        ocvdeltav = ocv1voltage - ocv2voltage;
                    }
                    else
                    {
                        Log.SystemError.Add("未查询到" + dr1[0]["cellno"].ToString() + "的OCV1数据!");
                    }

                    //将flag=6的ocv数据插入到MES中间表
                    try
                    {
                        mesmsg.InsertMESDCIRData(dr1[0]["trayno"].ToString(), finishtime, dr1[0]["cellno"].ToString(), i + 1, null, null, null, null, null, null, null, null, null, null, null, null, null, null,finishtime, ocv2voltage, ocvdeltav, null, null, null, 6);
                    }
                    catch (Exception ex)
                    {
                        Log.SQL.Add("将" + dr1[0]["trayno"].ToString() + "托盘的第" + i  + "通道的" + dr1[0]["cellno"].ToString() + "的OCV2数据插入到MES中间表失败!" + ex);
                    }

                }

            }

        }

        public void CloseCOMPORT()
        {
            try
            {
                SerialPort s = new SerialPort("COM4", 9600);
                if (s.IsOpen)
                {
                    s.Close();  
                }
            }
            catch (Exception)
            {
                richtbxmsg.AppendText("关闭串口失败\r\n");
            }
        }

        public void InitialAgilentEquip()
        {
            try
            {
                //初始化
                rm = new Ivi.Visa.Interop.ResourceManager();
                session = (IMessage)rm.Open("ASRL4::INSTR", AccessMode.NO_LOCK, 2000, "");
                ISerial ser = (ISerial)session;
                ser.BaudRate = 9600;
                ser.DataBits = 7;
                ser.StopBits = SerialStopBits.ASRL_STOP_ONE;
                ser.Parity = SerialParity.ASRL_PAR_EVEN;
                ser.FlowControl = SerialFlowControl.ASRL_FLOW_NONE;
                //// Read until LF(0x0A) byte for *IDN? response
                //session.WriteString("*IDN?\n");
                //strRd = session.ReadString(100);
                session.WriteString("INST:DMM ON\n");
                session.WriteString("CONF:VOLT:DC 10,0.00001,(@101:116)\n");
                session.WriteString("VOLT:DC:NPLC 10\n");
                session.WriteString("ROUT:SCAN (@101:116)\n");
                Thread.Sleep(200);
                session.WriteString("TRIG:SOURCE TIMER\n");
                session.WriteString("ROUT:CHAN:DELAY 0.1,(@101:116)\n");
                Thread.Sleep(200);
                session.WriteString("TRIG:COUN 1\n");
                session.WriteString("INIT\n");
                session.WriteString("FETCH?\n");
        
            }
            catch (Exception ex)
            {

                Log.SystemError.Add("初始化安捷伦设备失败!"+ex.ToString());
            }
                
        }

        //将电压转化成对应的科学计数法正确的值
        public Double TransVtoRight(string str, int keepno)  //keepno为保留位数.
        {
            int no = str.IndexOf("E");
            if (no > 0)
            {
                double v = 0;
                try
                {

                    v = double.Parse(str.Substring(0, no));
                    string ckno = str.Substring(no + 1);
                    ckno = double.Parse(ckno).ToString();
                    v = Math.Round(v * Math.Pow(10, Convert.ToDouble(ckno)), keepno);
                }
                catch
                {
                    //WriteLogTxt(ErrorLogPath, DateTime.Now + "将OCV,CASEV：" + str + "转化科学计数法失败");
                    richtbxmsg.AppendText("将OCV转化科学计数法失败\r\n");
                    return 99999;

                }
                Double str1 = Double.Parse(v.ToString("f" + keepno.ToString()));
                return str1;
            }
            else
            {
                double v = 0;
                try
                {
                    v = Convert.ToDouble(str);

                }
                catch
                {

                    richtbxmsg.AppendText("将OCV转化科学计数法失败\r\n");
                    return 99999;

                }

                Double str1 = Double.Parse(v.ToString("f" + keepno.ToString()));
                return str1;
            }


        }

        private void bgBeginOCVAgain_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                string rec510 = ReadRightValue("510", 1, "0001");
                //string traynotest = ReadTrayNo("530", 10, "notnull");
                if (rec510 == "0001")
                {
                    string trayno = ReadTrayNo("530", 10, "notnull");
                    if (trayno.Length >= 11)
                    {
                        trayno = trayno.Substring(0, 11);
                        tbxtrayno.Text = trayno;

                    }
                    else
                    {
                        continue;
                    }

                    if (trayno.Contains("C15"))
                    {
                        WriteRightValue("10", 1, 1);

                    }
                    else if (trayno.Contains("C12"))
                    {
                        WriteRightValue("10", 1, 2);

                    }
                    else if (trayno.Contains("C19"))
                    {
                        WriteRightValue("10", 1, 3);

                    }

                    WriteRightValue("10", 1, 1);

                    string receive510 = ReadRightValue("510", 1, "0000");
                    if (receive510 == "0000")
                    {
                        WriteRightValue("10", 1, 0);
                    }
                    else
                    {
                        msgwarn.Text = "PLC510应答异常";
                        msgwarn.BackColor = Color.Red;
                        continue;
                    }
                    Thread.Sleep(6000);
                    string rec511 = ReadRightValue("511", 1, "0001");
                    if (rec511 == "0001")
                    {
                        WriteRightValue("11", 1, 1);
                        string receive511 = ReadRightValue("511", 1, "0000");
                        if (receive511 == "0000")
                        {
                            WriteRightValue("11", 1, 0);
                            msgwarn.Text = "开始OCV测定";
                            msgwarn.BackColor = Color.SpringGreen;


                        }
                        else
                        {
                            msgwarn.Text = "PLC511复位失败";
                            msgwarn.BackColor = Color.Red;
                        }

                        Thread.Sleep(3000);
                        msgwarn.Text = "测定NG,即将开始再测试";
                        msgwarn.BackColor = Color.SpringGreen;

                        WriteRightValue("12", 1, 2);

                        string rec512 = ReadRightValue("512", 1, "0001");

                        if (rec512 == "0001")
                        {
                            WriteRightValue("12", 1, 0);

                            string receive512 = ReadRightValue("512", 1, "0000");
                            if (receive512 == "0000")
                            {
                                Thread.Sleep(2500);
                                string rd511 = ReadRightValue("511", 1, "0001");
                               
                                if (rd511 == "0001")
                                {
                                    WriteRightValue("11", 1, 1);
                                    //Thread.Sleep(200);
                                    string read511 = ReadRightValue("511", 1, "0000");
                                    //有必要
                                    Thread.Sleep(200);
                                    if (read511 == "0000")
                                    {
                                        WriteRightValue("11", 1, 0);
                                    }
                                    else
                                    {
                                        msgwarn.Text = "PLC511复位应答异常";
                                        msgwarn.BackColor = Color.Red;
                                    }
                                    msgwarn.Text = "开始OCV再测试";
                                    msgwarn.BackColor = Color.Yellow;
                                    Thread.Sleep(3000);
                                    WriteRightValue("12", 1, 1);
                                    Thread.Sleep(200);
                                    string rd512 = ReadRightValue("512", 1, "0001");

                                    if (rd512 == "0001")
                                    {
                                        WriteRightValue("12", 1, 0);
                                        msgwarn.Text = "OCV测试搬出完成";
                                        msgwarn.BackColor = Color.SpringGreen;

                                    }
                                    else
                                    {
                                        msgwarn.Text = "PLC512置1异常2";
                                        msgwarn.BackColor = Color.Red;
                                    }

                                }
                                else
                                {
                                    msgwarn.Text = "PLC511置1应答异常2";
                                    msgwarn.BackColor = Color.Red;
                                }
                            }
                            else
                            {
                                msgwarn.Text = "PLC512置0复位应答异常2";
                                msgwarn.BackColor = Color.Red;
                            }
                        }
                        else
                        {
                            msgwarn.Text = "PLC512置1应答异常1";
                            msgwarn.BackColor = Color.Red;
                        }



                    }
                    else
                    {
                        msgwarn.Text = "PLC511置1应答异常1";
                        msgwarn.BackColor = Color.Red;
                    }

                }

            }
        }

        private void bgBeginDCIRTest_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(500);
                string rec510 = ReadRightValue1("1510", 1, "0001");
                if (rec510 == "0001")
                {
                    
                    tbxdcirmsg.Text = "DCIR搬入中";
                    tbxdcirmsg.BackColor = Color.SpringGreen;
                    string trayno = ReadTrayNo1("1530", 10, "notnull");
                    if (trayno.Length >= 11)
                    {
                        trayno = trayno.Substring(0, 11);
                        tbxdcirtrayno.Text = trayno;

                    }
                    else
                    {

                        while (trayno.Length < 11)
                        {
                            trayno = ReadTrayNo1("1530", 10, "notnull");
                        }
                    }
                    if (trayno.Contains("C15"))
                    {
                        WriteRightValue2("1010", 1, 1);
                    }
                    else if (trayno.Contains("C12"))
                    {
                        WriteRightValue2("1010", 1, 2);
                    }
                    else if (trayno.Contains("C19"))
                    {
                        WriteRightValue2("1010", 1, 3);
                    }



                    string receive510 = ReadRightValue1("1510", 1, "0000");
                    if (receive510 == "0000")
                    {
                        WriteRightValue2("1010", 1, 0);
                    }
                    else
                    {
                        richtbxmsg.AppendText("PLC1510复位应答异常\r\n");
                        break;
                    }
                    while (ReadRightValue1("1511", 1, "notnull") != "0001")
                    {
                        Thread.Sleep(200);
                    }
                    
                    string rec511 = ReadRightValue1("1511", 1, "0001");
                    if (rec511 == "0001")
                    {
                        WriteRightValue2("1011", 1, 1);
                        string receive511 = ReadRightValue1("1511", 1, "0000");
                        if (receive511 == "0000")
                        {
                            WriteRightValue2("1011", 1, 0);
                        }
                        else
                        {
                            richtbxmsg.AppendText("DCIR测试PLC1511应答异常\r\n");
                            break;
                        }

                        if (allowdcir == 1)
                        {
                            tbxdcirmsg.Text = "开始DCIR测定";
                            tbxdcirmsg.BackColor = Color.SpringGreen;
                            //开始测定发送WTL和WTI,即将测定DCIR
                            bool wtlflag = kep.TrayLoad(trayno, "001001001");
                            int wtlngcount = 1;
                            //如果不升起就一直发送
                            if (!wtlflag)
                            {
                                richtbxmsg.AppendText("电源回复ETL异常，程序等待中!\r\n");
                                while (wtlflag == false && wtlngcount <= allowngcount)
                                {
                                    Thread.Sleep(50);
                                    wtlflag = kep.TrayLoad(trayno, "001001001");
                                    wtlngcount++;
                                }
                            }
                            if (handInput == true)
                            {
                                DataTable dttemp = new DataTable();
                                dttemp = TempDT.dt;
                                for (int i = 1; i <= 16; i++)
                                {
                                    DataRow dr = dttraycellinfo.NewRow();
                                    dr["chno"] = i;
                                    dr["trayno"] = trayno;
                                    DataRow[] dr1 = dttemp.Select("chno='" + i + "'");
                                    dr["cellno"] = dr1[0]["cellno"];

                                    dttraycellinfo.Rows.Add(dr);
                                }
                            }
                            
                            richtbxmsg.AppendText("已发送WTL，并且收到正确的ETL回复!\r\n");
                            bool sendtrayflag = kep.SendTrayInfo(trayno, dttraycellinfo);
                            if (!sendtrayflag)
                            {
                                richtbxmsg.AppendText("发送托盘信息失败，程序持续发送中!\r\n");
                                while (sendtrayflag == false)
                                {
                                    Thread.Sleep(500);
                                    sendtrayflag = kep.SendTrayInfo(trayno, dttraycellinfo);
                                }
                            }
                            //richtbxmsg.AppendText("发送托盘信息成功!\r\n");
                            dttraycellinfo.Clear();
                            while (!(GParam.RecListDic.ContainsKey("EPF") && GParam.RecStringDic.ContainsKey("EPF") && GParam.RecStringDic["EPF"].Length > 0))
                            {
                                Thread.Sleep(200);
                            }

                            if (GParam.RecListDic.ContainsKey("EPF") && GParam.RecStringDic.ContainsKey("EPF") && GParam.RecStringDic["EPF"].Length > 0)
                            {
                                richtbxmsg.AppendText("已收到充电完成信号\r\n");
                                bool wpfflag = kep.ProcessFinish();

                                if (!wpfflag)
                                {
                                    richtbxmsg.AppendText("回复充电完成信号异常\r\n");
                                    while (wpfflag == false)
                                    {
                                        Thread.Sleep(500);
                                        wpfflag = kep.ProcessFinish();
                                    }
                                }

                            }

                            richtbxmsg.AppendText("已回复充电完成信号\r\n");

                            tbxdcirmsg.Text = "DCIR测试完成,准备搬出";
                            tbxdcirmsg.BackColor = Color.SpringGreen;
                        }
                        else
                        {
                            tbxdcirmsg.Text = "已跳过DCIR测定";
                            tbxdcirmsg.BackColor = Color.Yellow;
                        }


                        WriteRightValue2("1012", 1, 1);

                        string rec512 = ReadRightValue1("1512", 1, "0001");

                        if (rec512 == "0001")
                        {
                            WriteRightValue2("1012", 1, 0);
                            tbxdcirmsg.Text = "DCIR测试搬出完成";
                            tbxdcirmsg.BackColor = Color.SpringGreen;
                            break;
                            //return;
                           
                        }
                        else
                        {
                            richtbxmsg.AppendText("PLC1512置1应答异常\r\n");
                           
                        }
                    }
                    else
                    {
                        richtbxmsg.AppendText("PLC1511应答异常\r\n");
                    }

                }

            }
        }

        private void bgBeginDCIRTestAgain_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                string rec510 = ReadRightValue2("1510", 1, "0001");
                if (rec510 == "0001")
                {
                    string trayno = ReadTrayNo1("1530", 10, "notnull");
                    if (trayno.Length >= 11)
                    {
                        trayno = trayno.Substring(0, 11);
                        tbxtrayno.Text = trayno;
                    }
                    else
                    {
                        continue;
                    }


                    if (trayno.Contains("C15"))
                    {
                        WriteRightValue1("1010", 1, 1);

                    }
                    else if (trayno.Contains("C12"))
                    {
                        WriteRightValue1("1010", 1, 2);

                    }
                    else if (trayno.Contains("C19"))
                    {
                        WriteRightValue1("1010", 1, 3);

                    }

                    WriteRightValue1("1010", 1, 1);
                    Thread.Sleep(200);
                    string receive510 = ReadRightValue2("1510", 1, "0000");
                    if (receive510 == "0000")
                    {
                        WriteRightValue1("1010", 1, 0);
                    }
                    else
                    {
                        msgwarn.Text = "PLCDCIR1510置0应答异常";
                        msgwarn.BackColor = Color.Red;
                        continue;
                    }
                    Thread.Sleep(2500);
                    string rec511 = ReadRightValue2("1511", 1, "0001");
                    if (rec511 == "0001")
                    {
                        WriteRightValue1("1011", 1, 1);
                        string receive511 = ReadRightValue2("1511", 1, "0000");
                        if (receive511 == "0000")
                        {
                            WriteRightValue1("1011", 1, 0);
                            msgwarn.Text = "开始DCIR测定";
                            msgwarn.BackColor = Color.SpringGreen;


                        }

                        Thread.Sleep(6000);
                        //msgwarn.Text = "测定NG,开始在测试";
                        //msgwarn.BackColor = Color.SpringGreen;

                        WriteRightValue1("1012", 1, 2);

                        string rec512 = ReadRightValue2("1512", 1, "0001");

                        if (rec512 == "0001")
                        {
                            WriteRightValue1("1012", 1, 0);

                            string receive512 = ReadRightValue2("1512", 1, "0000");
                            if (receive512 == "0000")
                            {
                                Thread.Sleep(2500);
                                string rd511 = ReadRightValue2("1511", 1, "0001");
                                if (rd511 == "0001")
                                {
                                    WriteRightValue1("1011", 1, 1);
                                    //Thread.Sleep(200);
                                    string read511 = ReadRightValue2("1511", 1, "0000");
                                    if (read511 == "0000")
                                    {
                                        WriteRightValue1("1011", 1, 0);
                                    }
                                    else
                                    {
                                        msgwarn.Text = "PLCDCIR1511置0应答异常2";
                                        msgwarn.BackColor = Color.Red;
                                    }
                                    msgwarn.Text = "开始DCIR再测试";
                                    msgwarn.BackColor = Color.Yellow;
                                    Thread.Sleep(3000);
                                    WriteRightValue1("1012", 1, 1);
                                    Thread.Sleep(200);
                                    string rd512 = ReadRightValue2("1512", 1, "0001");

                                    if (rd512 == "0001")
                                    {
                                        WriteRightValue1("1012", 1, 0);
                                        msgwarn.Text = "DCIR测试搬出完成";
                                        msgwarn.BackColor = Color.SpringGreen;
                                    }
                                    else
                                    {
                                        msgwarn.Text = "PLCDCIR1512置1应答异常2";
                                        msgwarn.BackColor = Color.Red;
                                    }

                                }
                                else
                                {
                                    msgwarn.Text = "PLCDCIR1511置1应答异常2";
                                    msgwarn.BackColor = Color.Red;
                                }
                            }
                            else
                            {
                                msgwarn.Text = "PLCDCIR1512置0应答异常";
                                msgwarn.BackColor = Color.Red;
                            }
                        }
                        else
                        {
                            msgwarn.Text = "PLCDCIR1512置1应答异常";
                            msgwarn.BackColor = Color.Red;
                        }



                    }
                    else
                    {
                        msgwarn.Text = "PLCDCIR1511置1应答异常1";
                        msgwarn.BackColor = Color.Red;
                    }

                }

            }
        }

        //校验并发送读指令
        public string ReadTrayNo1(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        msgwarn.Text = "网络连接断开";
                        msgwarn.BackColor = Color.Red;
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        msgwarn.Text = "网络连接断开";
                        msgwarn.BackColor = Color.Red;
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;
                    }

                }
            }

            Thread.Sleep(200);
            return recvalue;

        }

        //校验并发送读指令
        public string ReadRightValue1(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";
            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        //msgwarn.Text = "网络连接断开";
                        //msgwarn.BackColor = Color.Red;
                        richtbxmsg.AppendText("与PLC断开连接!!\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");

                        }

                        Thread.Sleep(200);
                        recvalue = st2.receivedata(eqno, "r");
                        ngcount++;
                        Thread.Sleep(200);

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        msgwarn.Text = "网络连接断开";
                        msgwarn.BackColor = Color.Red;
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            Thread.Sleep(200);
            return recvalue;

        }

        //校验并发送写指令
        public void WriteRightValue1(string eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st2.Connected() == false)
                {
                    msgwarn.Text = "网络连接断开";
                    msgwarn.BackColor = Color.Red;
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st2.Connected() == false)
                    {
                        ReConnect2();
                    }

                }
                else if (st2.Connected())
                {
                    sendflag = st2.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st2.receivedata(1, "w");
                    ngcount++;

                }

            }
            Thread.Sleep(200);

        }

        private void button2_Click_2(object sender, EventArgs e)
        {
            //splitData("+3.26770410E+00,+3.27504940E+00,+1.91800000E-04,+1.34300000E-04,+6.93000000E-05,+1.84400000E-04,+1.72700000E-04,+9.49000000E-05,+1.15100000E-04,+1.02740000E-03,+1.99300000E-04,+8.53000000E-05,+1.37590000E-03,+4.27757600E-01,+3.61932500E-01,+7.99000000E-05");
            //string testresult = "+3.26770410E+00,+3.27504940E+00,+1.91800000E-04,+1.34300000E-04,+6.93000000E-05,+1.84400000E-04,+1.72700000E-04,+9.49000000E-05,+1.15100000E-04,+1.02740000E-03,+1.99300000E-04,+8.53000000E-05,+1.37590000E-03,+4.27757600E-01,+3.61932500E-01,+7.99000000E-05";
            //string[] list = splitData(testresult);
            //CreateOCVCsv("H003239-C12", list);
           // string trayno = ReadTrayNo("530", 10, "notnull");
            msgwarn.Text = "";
            msgwarn.BackColor = Color.White;
            tbxtrayno.Text = "";
            richtbxmsg.Text = "";
            tbxdcirmsg.Text = "";
            tbxdcirmsg.BackColor = Color.White;
            tbxdcirtrayno.Text = "";
            //WriteRightValue1("10",1,0);
            //string trayno = ReadTrayNo("530", 10, "notnull");
            //WriteRightValue1("10",1,0);
            //WriteRightValue1("11",1,0);
            //WriteRightValue1("12",1,0);
            //WriteRightValue1("1010", 1, 0);
            //WriteRightValue1("1011", 1, 0);
            //WriteRightValue1("1012", 1, 0);





            //msgwarn.Text = "测定OK，开始搬出";
            //msgwarn.BackColor = Color.SpringGreen;
            //WriteRightValue("12", 1, 1);
            //string rec512 = ReadRightValue("512", 1, "0001");

            //if (rec512 == "0001")
            //{
            //    WriteRightValue("12", 1, 0);
            //    msgwarn.Text = "OCV测试搬出完成";
            //    msgwarn.BackColor = Color.SpringGreen;

            //    return;
            //}
            //else
            //{
            //    msgwarn.Text = "PLC应答异常";
            //    msgwarn.BackColor = Color.Red;
            //}
        }

        private void 参数设定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FmArgSetting fmarg = new FmArgSetting();
            fmarg.Show();
        }

        private void timerRefreshArgSetting_Tick(object sender, EventArgs e)
        {
            bgRefreshArgSetting.RunWorkerAsync();
        }

        private void bgRefreshArgSetting_DoWork(object sender, DoWorkEventArgs e)
        {
            CreateArgXmlFile();
        }

        private void button3_Click_2(object sender, EventArgs e)
        {
            //FmScanTray scantray = new FmScanTray();
            //scantray.ShowDialog();
            //if (TempDT.dt.Rows.Count <= 0)
            //{
            //    MessageBox.Show("请先扫电池条码");
            //    return;
            //}
            //if (bgBeginOCV.IsBusy || bgBeginDCIRTest.IsBusy)
            //{
            //    MessageBox.Show("正在测量中!");
            //    return;
            //}

            //bgBeginOCV.RunWorkerAsync(TempDT.dt);
            for (int i = 0; i < 16; i++)
            {
                DataRow dr = dtocvdata.NewRow();
                dr["cellno"] = "HQFHSBQWE111"+(i+1).ToString().PadLeft(2,'0');
                dr["chno"] =i+1;
                dr["ocvdata"] =0.34-(0.01*i);
                dr["cellsts"] ="OK";
                dtocvdata.Rows.Add(dr);
            }
            DataTable dttest = dtocvdata.Clone();
            for (int i = 0; i < dtocvdata.Rows.Count; i++)
            {
                dttest.ImportRow(dtocvdata.Rows[i]);
            }
            dtocvdata.Clear();
            this.Invoke(new Action(() =>
            {
                dgvocvdata.DataSource = dttest.Copy();
                

            }));

            return;
        }

        //创建或获取XML的指定的地址
        public void CreateArgXmlFile()
        {
            XmlDocument xmlDoc = new XmlDocument();
            string XMLPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            XMLPath = XMLPath + "\\" + "ArugmentSetting.xml";
            //如果不存在导出路径XML的话则创建。
            if (!File.Exists(XMLPath))
            {
                //创建类型声明节点  
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
                xmlDoc.AppendChild(node);
                //创建根节点  

                XmlNode root = xmlDoc.CreateElement("参数");
                xmlDoc.AppendChild(root);
                //string SysPath = ArgSetPath;
                CreateNode(xmlDoc, root, "允许OCV测试", "1");
                CreateNode(xmlDoc, root, "允许DCIR测试", "1");
                CreateNode(xmlDoc, root, "OCV下限", "1");
                CreateNode(xmlDoc, root, "OCV上限", "3");

                try
                {
                    XMLPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    XMLPath = XMLPath + "\\" + "ArugmentSetting.xml";
                    xmlDoc.Save(XMLPath);
                    return;
                }
                catch (Exception e)
                {
                    //显示错误信息  
                    Console.WriteLine(e.Message);
                }

            }
            else
            {
                //XMLPath = XMLPath + "\\" + "ArugmentSetting.xml";
                xmlDoc.Load(XMLPath);
                //获取某个节点
                XmlNode allowocv1 = xmlDoc.SelectSingleNode("参数").SelectSingleNode("允许OCV测试");
                XmlNode allowdcir1 = xmlDoc.SelectSingleNode("参数").SelectSingleNode("允许DCIR测试");
                XmlNode ocvlow1 = xmlDoc.SelectSingleNode("参数").SelectSingleNode("OCV下限");
                XmlNode ocvhigh1 = xmlDoc.SelectSingleNode("参数").SelectSingleNode("OCV上限");


                //判断OCV,ACIR,TEMP,CASEV  NG是否选中
                allowocv = int.Parse(allowocv1.InnerText);
                allowdcir = int.Parse(allowdcir1.InnerText);
                ocvlow = Double.Parse(ocvlow1.InnerText);
                ocvhigh = Double.Parse(ocvhigh1.InnerText);
               

            }
            return;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ////double dbtemp = TransVtoRight("7.99000000E-05", 6);
            //string trayno = "H031637-C19";
            //DataTable dttrayinfo = new DataTable();
            //    //dttrayinfo = trayinfo.GetCellNoByTrayNo(trayno);
            //    string testresult = "+3.26770200E+00,+3.27504720E+00,+1.87600000E-04,+1.26800000E-04,+7.46000000E-05,+1.83300000E-04,+1.70500000E-04,+1.25800000E-04,+1.16200000E-04,+1.02530000E-03,+1.97200000E-04,+8.21000000E-05,+1.37910000E-03,+4.27781100E-01,+3.61964500E-01,+7.99000000E-05";
            //    string[] list = splitData(testresult); 
            //if (dttrayinfo.Rows.Count > 0 )
            //{
            //    //将托盘信息级电池NG结果存储到dttraycellinfok
            //    for (int i = 0; i < dttrayinfo.Rows.Count; i++)
            //    {

            //        DataRow dr = dttraycellinfo.NewRow();
            //        dr["trayno"] = trayno;
            //        dr["cellno"] = "";
            //        dr["cellsts"] = JudgeCellSts(Double.Parse(list[i]));
            //        dttraycellinfo.Rows.Add(dr);
            //    }


            //    //创建OCV cvs
            //    //CreateOCVCsv(dttraycellinfo, trayno, list, starttime, endtime);
            //    //将OCV测定结果存储到DB
            //    //SaveOCVDataToDB(trayno, list, dttrayinfo);
            //}
            //else
            //{
            //    Log.SystemError.Add("根据托盘号查询电池条码失败！");
            //}


            //kep.SendTrayInfo(trayno, dttraycellinfo);
            //dttraycellinfo.Clear();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //iSocket.DisConnectClient();
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            //double dbtemp = TransVtoRight("7.99000000E-05", 6);
            
            //iSocket.ClosedConnect();
            dttraycellinfo.Clear();
            for (int i = 1; i <= 16; i++)
            {
                DataRow dr = dttraycellinfo.NewRow();
                dr["chno"] = i;
                dr["cellno"] = "HQI19C15GRNS0122" + i.ToString().PadLeft(2, '0');
                if (i == 10 || i == 14)
                {
                    dr["cellsts"] = "05";
                }
                else
                {
                    dr["cellsts"] = "00";
                }
                
                dttraycellinfo.Rows.Add(dr);
            }
            bool sendtrayflag = kep.SendTrayInfo("H024153-C19", dttraycellinfo);
            if (!sendtrayflag)
            {
                richtbxmsg.AppendText("发送托盘信息失败，程序持续发送中!\r\n");
                while (sendtrayflag == false)
                {
                    sendtrayflag = kep.SendTrayInfo("H024153-C15", dttraycellinfo);
                }
            }

        }

        private void button4_Click_2(object sender, EventArgs e)
        {
            try
            {
                if (!kep.SynchronizeTime())
                {
                    Exceptionlog.InsertException("同步时间异常", "与电源通讯同步系统时间时，电源响应为：erro。");
                }

            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);
            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Alt) != 0 && (Control.ModifierKeys & Keys.Control) != 0 && (Control.ModifierKeys & Keys.Shift) != 0 && e.KeyCode == Keys.D0)
            {
                if (btCheckLink.Visible == true )
                {
                    btCheckLink.Visible = false;
                   
                }
                else
                {
                    btCheckLink.Visible = true;
                    
                }
            }
        }

        private void bgBeginOCV_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //richtbxmsg.AppendText("OCV测定完成，来自bgBeginOCV\r\n"); 
            //MessageBox.Show("OCVBackGround Is Finish");
        }

        private void bgBeginDCIRTest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //richtbxmsg.AppendText("DCIR测定完成，来自bgBeginDCIRTest\r\n"); 
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            bgTestOcv.RunWorkerAsync();
        }

        private void bgTestOcv_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
               

                testresult = AgilentMeasure();
                while (testresult == "")
                {
                    msgwarn.Text = "OCV再测试中";
                    msgwarn.BackColor = Color.Yellow;
                    Thread.Sleep(500);
                    starttime = DateTime.Now;

                    testresult = AgilentMeasure();
                }
                msgwarn.Text = "OCV测定完成!";
                msgwarn.BackColor = Color.SkyBlue;

                try
                {
                    string[] list = splitData(testresult);
                    if (list.Length == 0)
                    {
                        msgwarn.Text = "读取OCV测试数据异常";
                        msgwarn.BackColor = Color.Red;
                        return;
                    }

                }
                catch (Exception ex)
                {

                    richtbxmsg.AppendText("生成OCV测定结果失败\r\n");
                    Log.SystemError.Add("生成OCV测定结果失败" + ex.ToString());
                }
            }
        }

        private void 工艺设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FmRecipeSet recipeset = new FmRecipeSet();
            recipeset.Show();
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChangePass pass = new FormChangePass();
            pass.Show();
        }

     

        
    }
}
